/* (c)2010-2011 Andrea Caltroni (andrea.caltroni@pd.infn.it), INFN (www.infn.it)
 *
 * This file is part of the IGI Survey Portlet (from here on shortened to IGISP).
 * IGISP is free software: you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) any 
 * later version.
 *
 * IGISP is distributed in the hope that it will be useful, but WITHOUT ANY 
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with IGISP. If not, see <http://www.gnu.org/licenses/>.
 */
package it.infn.grid.liferay.survey.modules.admin.web;

import java.util.HashSet;
import java.util.Set;

import org.ajm.spring.survey.modules.admin.model.Question;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Validator for the form to change the order of questions of a survey.
 * 
 * @author Andrea Caltroni, andrea.caltroni@pd.infn.it, INFN
 */
@Component("changeQuestionOrderValidator")
public class ChangeQuestionOrderValidator implements Validator {

    // ------------------------------------------------------------------------|
    
    /**
     * @see org.springframework.validation.Validator#supports(java.lang.Class)
     */
    public boolean supports(Class<?> clazz) {
        
        return ChangeQuestionOrderCommand.class.equals(clazz);
    }

    // ------------------------------------------------------------------------|
    
    /**
     * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
     */
    public void validate(Object obj, Errors errors) {
        
        ChangeQuestionOrderCommand cqoCommand = (ChangeQuestionOrderCommand) obj;
        
        Set<Integer> positioncheckSet = new HashSet<Integer>();
        
        for (Question question : cqoCommand.getQuestions()) {
            int position = question.getPosition();
            if (!positioncheckSet.contains(position)) {
                positioncheckSet.add(position);
            }
            else {
                errors.reject("question.orderChange.duplicate");
                break;
            }
        }
    }

    // ------------------------------------------------------------------------|
    
}
